package com.atguigu.cloud.mygateway;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Component
@Slf4j
public class MyGlobalFilter implements GlobalFilter, Ordered {

    private static final String REQUEST_TIME = "request_time";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(REQUEST_TIME, System.currentTimeMillis());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            Long requestTime = exchange.getAttribute(REQUEST_TIME);
            if (Objects.nonNull(requestTime)) {
                log.info("接口调用耗时: {}毫秒", System.currentTimeMillis() - requestTime);
            }
        }));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
